import cv2 as cv  # pip install opencv-python
import os
import time
import threading

class CameraCapture(threading.Thread):
    def __init__(self,floder_name):
        threading.Thread.__init__(self)
        self.folder_name = floder_name
        self.__RunFlag = False

    def run(self):
        self.__RunFlag = True
        img_folder = 'pic' + time.strftime("%Y%m%d%H%M",time.localtime(time.time()))
        img_folder = os.path.join(self.folder_name,img_folder)
        if not os.path.exists(img_folder):
            os.mkdir(img_folder)
        print('start camera')
        cap = cv.VideoCapture(0)  # 打开摄像头
        num = 0
        start_time = time.time()
        while self.__RunFlag:
            ret,img = cap.read() # 读图片，ret:True/False,代表读成功与否 img:为当前获取的一帧
            cap.imshow('Video',img) # show出图片窗口
            end_time = time.time()
            pic_time = int((end_time - start_time)*1000)
            img_name = str(num) + '_' +str(pic_time) + '.jpg'
            img_path = os.path.join(img_folder,img_name)
            cap.imwrite(img_path,img)
            num += 1
            cap.waitKey(1)
        cap.release()  # 释放摄像头
        cv.destroyAllWindows()  # 结束所有窗口
        print("capture video end, destroy Windows")


    def stop(self):
        self.__RunFlag = False










